package com.hmall.filters;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmall.common.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author HOLO
 * @create 2023-01-09 3:29
 * @discription
 */

/**
 *  这是一个拦截器
 */
@Slf4j
public class CommonInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String id = request.getHeader("userId");
        if (StringUtils.isBlank(id)) {
            //无权登录
            log.warn("No is USER",request.getRequestURI());
            response.setStatus(403);
            return false;
        }

        UserHolder.setUser(Long.valueOf(id));
        //放行
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
